package com.yc.framework.bizClass;

import com.yc.framework.baseClass.R;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.util.WebUtils;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 *
 * @ClassName: 文件上传下载控制器
 * @Description:上传下载文件控制器
 * @author: 优驰科技-老顾
 * @date: 2018-4-27 上午11:51:40
 *
 * @Copyright: 2018 www.youchisoft.com Inc. All rights reserved.
 *             注意：本内容仅限于优驰软件科技无锡有限公司内部传阅，禁止外泄以及用于其他的商业目
 */
//@RestController
public class FileUploadController1 {

    /**
     * 异步请求方式上传文件:请求路径为"/upload/xxx",xxx为文件保存路径的一部份,如：files
     *
     * @param req
     * @param file
     * @param uploadPath
     * @return 文件保存位置的相对路径
     */
    @PostMapping("/upload/{uploadPath}")
    public R upload(MultipartHttpServletRequest req, MultipartFile file, @PathVariable String uploadPath) {
        try {
            if (null != file) {
                String name = String.format("%s%s", UUID.randomUUID().toString().toLowerCase(),
                        file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")));
                String path = "file/" + uploadPath + new SimpleDateFormat("/yyyy/MM/dd/").format(new Date());
                // DateFormatUtils.format(new Date(), "yyyy/MM/dd/");
                String pathName = path + name;
                ServletContext context = req.getSession(true).getServletContext();
                String realPath = getServletContextPath(context) + path;
                File dir = new File(realPath);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                File f = new File(realPath, name);
                FileUtils.writeByteArrayToFile(f, file.getBytes());
                System.out.println(realPath);
                return R.ok().put("pathName", pathName);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.err("上传失败");
    }

    @GetMapping("/download")
    public R downloadFile(String fullFileName, String fileName, final HttpServletResponse response,
                          final HttpServletRequest request) {
        OutputStream os = null;
        InputStream is = null;
        try {
            // 取得输出流
            os = response.getOutputStream();
            // 清空输出流
            response.reset();
            response.setContentType("application/x-download;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName); // URLEncoder.encode(fileName,
            System.out.println(URLDecoder.decode(fullFileName, "UTF-8")); // "UTF-8"));
            System.out.println(URLDecoder.decode(fileName, "UTF-8"));
            // 读取流
            ServletContext context = request.getSession(true).getServletContext();
            String realPath = getServletContextPath(context) + URLDecoder.decode(fullFileName, "UTF-8");
            File f = new File(realPath);
            System.out.println(f.exists());
            is = new FileInputStream(f);
            // 复制
            IOUtils.copy(is, response.getOutputStream());
            response.getOutputStream().flush();
        } catch (IOException e) {
            e.printStackTrace();
            return R.err().put("message", "下载附件失败,error:" + e.getMessage());
        }
        // 文件的关闭放在finally中
        finally {
            try {
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
            }
            try {
                if (os != null) {
                    os.close();
                }
            } catch (IOException e) {
            }
        }
        return null;
    }

    public static String getServletContextPath(ServletContext context) throws FileNotFoundException {
        String ctxPath = WebUtils.getRealPath(context, File.separator);
        if (!ctxPath.endsWith(File.separator)) {
            ctxPath = ctxPath + File.separator;
        }
        return ctxPath;
    }
}